// pages/intervalSetting/intervalSetting.js

const btUtils = require("../../utils/btUtils.js")
const utils = require("../../utils/util.js")

const READ_PERIOD_1 = "5AA5048105098F"
const READ_PERIOD_2 = "5AA5048114099E"
const READ_PERIOD_3 = "5AA504812309AD"

var suuid;
var cuuid;
var deviceId;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    period_index: 0,
    period: ["时间段1", "时间段2", "时间段3"],
    run_interval: 10,
    stop_interval: 10,
    startTime: "选择开始时间",
    endTime: "选择结束时间",
    status_enable: false,
    status_un_enable: false,
    week_1: false,
    week_2: false,
    week_3: false,
    week_4: false,
    week_5: false,
    week_6: false,
    week_7: false
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    console.log("参数是：", options);
    deviceId = options.deviceId
    suuid = options.suuid
    cuuid = options.cuuid
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.lisentCharateristicValue();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
  
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },
  /**
   * 绑定监听
   */
  lisentCharateristicValue: function () {

    //搞个事件总线 eventBUs, 解决多个界面去绑定蓝牙监听的问题
    var page = this;
    //监听特征值， 必须启用监听功能才能收到变化
    //res 中 deviceId, serviceId, characteristicId, value
    wx.onBLECharacteristicValueChange(function (res) {

      console.log("已有数据返回：in interval settings.js");

      //先判断是不是 OK, 判断长度
      if (res.value.byteLength <= 4) {
        var str = utils.ab2str(res.value);
        console.log("转换成字符串是:" + str);
        wx.showToast({
          title: '操作成功:' + str,
        })
        return;
      }

      var hex = utils.ab2hex(res.value);
      console.log("接收到的数据是:", hex);

      var data = btUtils.parseHex(hex)

      if (!data) {
        console.log("数据解析失败:" + hex);
        wx.showToast({
          title: '数据解析失败!',
        })
        return
      }

      console.log("解析出来的数据是：", data)

      //解析数据
      // 0 时段1开始时
      // 1 时段1开始分
      // 2 时段1停止时
      // 3 时段1停止分
      // 4 时段1运行秒高位
      // 5 时段1运行秒低位
      // 6 时段1停止秒高位
      // 7 时段1停止秒低位
      // 8 时段1星期运行开关, 0位是启用， 1-7星期
      let startTime = parseInt(data.dataArray[0], 16) + ":" + parseInt(data.dataArray[1], 16)
      let endTime = parseInt(data.dataArray[2], 16) + ":" + parseInt(data.dataArray[3], 16)

      let runTimes_hex = data.dataArray[4] + data.dataArray[5]
      let runTimes = parseInt(runTimes_hex, 16);

      let stopTimes_hex = data.dataArray[6] + data.dataArray[7]
      let stopTimes = parseInt(stopTimes_hex, 16);

      //先转整形
      let week_swicth = parseInt(data.dataArray[8], 16)

      //位运算得出每个位的值
      let enable = week_swicth & 1    //00000001
      let week_1 = week_swicth & 2    //00000010
      let week_2 = week_swicth & 4    //00000100
      let week_3 = week_swicth & 8    //00001000
      let week_4 = week_swicth & 16    //00010000
      let week_5 = week_swicth & 32    //0010000
      let week_6 = week_swicth & 64    //01000000
      let week_7 = week_swicth & 128    //10000000

      page.setData({
        run_interval: runTimes,
        stop_interval: stopTimes,
        startTime: startTime,
        endTime: endTime,
        status_enable: enable ? true : false,
        week_1: week_1 ? true : false,
        week_2: week_2 ? true : false,
        week_3: week_3 ? true : false,
        week_4: week_4 ? true : false,
        week_5: week_5 ? true : false,
        week_6: week_6 ? true : false,
        week_7: week_7 ? true : false
      });
    });
  },
  /**
   * 时段选项切换
   */
  periodSelected: function(event){
    this.setData({
      period_index: event.detail.value
    })
  },
  readSettings: function(){
    //根据当前选择的时段确定访问地址
    let pIndex = this.data.period_index;
    var command;
    if(pIndex == 0){
      command = READ_PERIOD_1
    }else if(pIndex == 1){
      command = READ_PERIOD_2
    }else if(pIndex == 2){
      command = READ_PERIOD_3
    }

    var value = utils.hex2ab(command);

    wx.writeBLECharacteristicValue({
      deviceId: deviceId,
      serviceId: suuid,
      characteristicId: cuuid,
      value: value,
      success: function (errMsg){
        // wx.showToast({
        //   title: '请求成功，等待返回结果：' + errMsg,
        // })
      },
      fail: function (errMsg){
        wx.showToast({
          title: '数据访问请求写入失败：' + errMsg,
        })
      }
    })
  },
  writteSettings: function(){
    //根据当前选择的时段确定访问地址
    let pIndex = this.data.period_index;
    var address = pIndex * 9 + 5;  //每个时段读9个
    address = "" + address
    if(address.length == 1){
      address = "0" + address;
    }

    //获取各项数据
    //开始时间
    let startHour = this.data.startTime.split(":")[0];
    let startMinute = this.data.startTime.split(":")[1];

    //停止时间
    let stopHour = this.data.endTime.split(":")[0];
    let stopMinute = this.data.endTime.split(":")[1];

    console.log("stop hour is :" + stopHour + " hex :" + utils.intTo2Hex(stopHour))

    //运行时间
    let runTimes_hex = utils.intTo4Hex(this.data.run_interval);
    let stopTimes_hex = utils.intTo4Hex(this.data.stop_interval);

    //星期开关
    let week = 0;
    week = week | (this.data.status_enable ? 1 : 0);  //是否启用
    week = week | (this.data.week_1 ? 2 : 0);
    week = week | (this.data.week_2 ? 4 : 0);
    week = week | (this.data.week_3 ? 8 : 0);
    week = week | (this.data.week_4 ? 16 : 0);
    week = week | (this.data.week_5 ? 32 : 0);
    week = week | (this.data.week_6 ? 64 : 0);
    week = week | (this.data.week_7 ? 128 : 0);

    let dataArray = []
    dataArray.push(utils.intTo2Hex(startHour))
    dataArray.push(utils.intTo2Hex(startMinute))
    dataArray.push(utils.intTo2Hex(stopHour))
    dataArray.push(utils.intTo2Hex(stopMinute))
    dataArray.push(runTimes_hex[0] + runTimes_hex[1])
    dataArray.push(runTimes_hex[2] + runTimes_hex[3])
    dataArray.push(stopTimes_hex[0] + stopTimes_hex[1])
    dataArray.push(stopTimes_hex[2] + stopTimes_hex[3])
    dataArray.push(utils.intTo2Hex(week))

    let value_hex = btUtils.encodeWritte(address, dataArray);
    console.log("写入设备的数据是：", value_hex)
    let value_ab = utils.hex2ab(value_hex);

    wx.writeBLECharacteristicValue({
      deviceId: deviceId,
      serviceId: suuid,
      characteristicId: cuuid,
      value: value_ab,
      success: function (errMsg) {
        // wx.showToast({
        //   title: '请求成功，等待返回结果：' + errMsg,
        // })
      },
      fail: function (errMsg) {
        wx.showToast({
          title: '数据访问请求写入失败：' + errMsg,
        })
      }
    })
  },
  onStartTimePeckerSelect: function(e){

    let time = e.detail.value
    this.setData({
      startTime: time
    })
  },
  onEndTimePeckerSelect: function(e){

    let time = e.detail.value
    this.setData({
      endTime: time
    })
  },
  statusChange: function (e) {
    console.log(e)
    let value = e.detail.value

    this.setData({
      status_enable: (value == 1) ? true : false
    })
  },
  weekChange: function(e) {
    console.log(e)
    let array = e.detail.value;
    let data = {
      week_1: false,
      week_2: false,
      week_3: false,
      week_4: false,
      week_5: false,
      week_6: false,
      week_7: false
    };

    for(let value of array){

      switch(value){
        case "1":
          data.week_1 = true
          break
        case "2":
          data.week_2 = true
          break
        case "3":
          data.week_3 = true
          break
        case "4":
          data.week_4 = true
          break
        case "5":
          data.week_5 = true
          break
        case "6":
          data.week_6 = true
          break
        case "7":
          data.week_7 = true
          break
        default:
      }
    }

    this.setData(data);
  },
  runTimesChange: function(e){
    let value = e.detail.value
    this.setData({
      run_interval: value
    })
  },
  stopTimesChange: function(e){
    let value = e.detail.value
    this.setData({
      stop_interval: value
    })
  }
})